<template>
  <div class="mineSetUpStyle">
    <el-card>
      <div class="pickerOptionSet">
        <span style="font-weight: bold">店铺管理</span>
        <el-button style="font-weight: bold" size="mini" type="primary" @click="addTerminalSet">新建终端</el-button>
      </div>
    </el-card>
    <el-card>
      <span>产地区:</span>
      <el-select class="selectFont" size="mini" @change="getProvinceSet" placeholder="选择地区" v-model="area.chooseArea" style="width: 100px;">
        <el-option class="selectFont" v-for="item in area.area" :key="item" :label="item" :value="item"></el-option>
      </el-select>
      <el-select class="selectFont" size="mini" placeholder="选择省份" @change="getCitySet" v-model="area.chooseProvince" style="width: 100px;">
        <el-option class="selectFont" v-for="(item,index) in area.province" :key="index" :label="item" :value="item"></el-option>
      </el-select>
      <el-select class="selectFont" size="mini" placeholder="选择城市" @change="getDataPage(1)" v-model="area.chooseCity" style="width: 100px;">
        <el-option class="selectFont" v-for="(item,index) in area.city" :key="index" :label="item" :value="item"></el-option>
      </el-select>
      <span style="margin-left: 6px;">卖场类型:</span>
      <el-select  class="selectFont" size="mini" placeholder="选择渠道" @change="getDataPage(1)" v-model="channelType" style="width: 100px;margin-right:30px">
        <el-option class="selectFont" label="全部" value="全部"></el-option>
        <el-option class="selectFont" label="线上" value="线上"></el-option>
        <el-option class="selectFont" label="线下" value="线下"></el-option>
      </el-select>
      <el-input size="mini" v-model="select.channelName" style="width:150px"  placeholder="渠道名称"></el-input>
      <el-button style="font-weight: bold" size="mini" type="primary" @click="getDataPage(1)">查询</el-button>
      <div class="pickerOption">
        <span >共{{totalRecord}}条数据&nbsp;&nbsp;</span>
        <el-button  style="margin:0 10px;font-weight: bold" size="mini" type="ghost" @click="dialogVisible1 = true;">模板下载</el-button>
        <el-button style="font-weight: bold" size="mini" type="ghost" @click="dialogVisible = true;">导入终端</el-button>
      </div>
      <el-dialog class="dialogHeaderFont" title="模板导入" :visible.sync="dialogVisible" width="30%">
        <el-upload class="upload-demo" action="/front/excelUpload?method=onlineImportProduct"
                    :data="dataSetParam" :on-success="handleSuccessWord" :show-file-list="false"
                    accept=".xlsx,.xls" :file-list="fileList" :headers="headersSet">
           <el-button style="font-weight: bold" size="small" type="primary">点击上传线上模板</el-button>
           <div slot="tip" class="el-upload__tip"></div>
        </el-upload>
        <br/>
        <el-upload class="upload-demo" action="/front/excelUpload?method=offlineImportProduct"
                    :data="dataSetParam" :on-success="handleSuccessWord" :show-file-list="false"
                    accept=".xlsx,.xls" :file-list="fileList" :headers="headersSet">
          <el-button style="font-weight: bold" size="small" type="primary">点击上传线下模板</el-button>
          <div slot="tip" class="el-upload__tip"></div>
        </el-upload>
       </el-dialog>
      <el-dialog title="模板下载" class="dialogHeaderFont upload-demo" :visible.sync="dialogVisible1" width="30%">
         <el-button style="font-weight: bold" size="small" type="primary" @click="downLoadDoc('终端管理-线上')">点击下载线上模板</el-button>
         <br/>
         <el-button style="font-weight: bold" size="small" type="primary" @click="downLoadDoc('终端管理-线下')">点击下载线下模板</el-button>
      </el-dialog>
    </el-card>
    <el-card>
      <div style="border: 1px solid #e3e2e2;border-top: 0">
        <el-table :data="tableDataSet" stripe style="width: 100%;margin-top:20px" size="mini">
          <el-table-column
            prop="channelName"
            label="渠道名">
          </el-table-column>
          <el-table-column
            prop="shopName"
            min-width="120px"
            label="店铺名">
          </el-table-column>
          <el-table-column
            prop="channelType"
            width="90px"
            label="渠道属性">
          </el-table-column>
          <el-table-column
            prop="region"
            label="地区">
          </el-table-column>
          <el-table-column
            prop="city"
            label="城市">
          </el-table-column>
          <el-table-column
            prop="province"
            label="省份">
          </el-table-column>
          <el-table-column
            prop="contactName"
            sortable
            min-width="92px"
            label="联系人">
          </el-table-column>
          <el-table-column
            min-width="112px"
            prop="contactPhone"
            label="联系电话">
          </el-table-column>
          <el-table-column
            prop="createTime"
            min-width="160px"
            label="创建时间"
            sortable>
          </el-table-column>
          <el-table-column
            prop="status"
            min-width="75"
            label="状态"
            sortable>
             <template slot-scope="scope">
                <el-tag :type="scope.row.status | statusFilter">{{scope.row.status}}</el-tag>
             </template>
          </el-table-column>
          <el-table-column
            prop="name"
            min-width="135px"
            label="操作">
            <template slot-scope="scope">
              <el-button size="small" type="text" v-if="scope.row.status === '启用'" @click="editShop(scope.row.shopIdString,scope.row.status)">停用</el-button>
              <el-button size="small" type="text" v-else @click="editShop(scope.row.shopIdString,scope.row.status)">启用</el-button>
              <el-button size="small" type="text" @click="getTOrganizationDetail(scope.row.shopIdString)">编辑详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="paginationSet">
          <div class="pagination-container">
            <div class="toStart" @click="getDataPage(1)">首页</div>
            <el-pagination background layout="prev, pager, next"
                           @current-change="getDataPage" :current-page.sync="pageNumber" :total="totalRecord"></el-pagination>
          </div>
        </div>
      </div>

    </el-card>
    <el-dialog class="dialogHeaderFont" :title="updateTitle" top="8vh" :visible.sync="dialogVisibleUpdate" width="40%">
      <el-form ref="form" :model="formMineSet" label-width="120px" size="small">
        <el-form-item label="店铺图片">
          <el-upload action="/file/uploadFile" list-type="picture-card"
                     :data="dataSetParam1" :on-remove="handleRemove" :on-success="imgSuccess"
                     :show-file-list="showFlag" :file-list="fileList2"
                     :multiple="false" accept="image/*" :auto-upload="true"
                     :before-upload="beforeAvatarUpload"
                     :limit='1' name="file" :headers="headersSet">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group class="radioFont" v-model="formMineSet.status">
            <el-radio label="启用"></el-radio>
            <el-radio label="停用"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="终端名称">
          <el-input type="text" v-model="formMineSet.shopName" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="终端编号">
          <el-input type="text" v-model="formMineSet.shopNumber" maxlength="12"></el-input>
        </el-form-item>
        <el-form-item label="所属组织机构">
          <el-select placeholder="选择组织机构" v-model="formMineSet.organizationName" style="width: 100%;">
            <el-option v-for="item in getTOrganizations" :label="item.label" :value="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地区">
          <el-row>
            <el-col :span="8">
              <div class="grid-content bg-purple">
                <el-select @change="getProvinceUpdate" v-model="formMineSet.region" style="width: 100%;">
                  <el-option v-for="item in area.area1" :key="item"
                             :label="item" :value="item">
                  </el-option>
                </el-select>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="grid-content bg-purple">
                <el-select placeholder="选择省份" @change="getCityUpdate" v-model="formMineSet.province" style="width: 100%;">
                  <el-option v-for="(item,index) in area.province1"
                             :key="item" :label="item" :value="item"></el-option>
                </el-select>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="grid-content bg-purple">
                <el-select placeholder="选择城市" @change="getDistrict" v-model="formMineSet.city" style="width: 100%;">
                  <el-option v-for="(item,index) in area.city1" :key="index"
                             :label="item" :value="item"></el-option>
                </el-select>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="区域">
          <el-select placeholder="选择区域" v-model="formMineSet.district" style="width: 100%;">
            <el-option v-for="item in area.districts"
                       :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input :autosize="{ minRows: 1, maxRows: 8}" type="textarea" v-model="formMineSet.detailAddress"></el-input>
        </el-form-item>
        <el-form-item label="渠道">
          <el-select placeholder="选择渠道"
                     v-model="formMineSet.channelName" style="width: 100%;">
            <el-option v-for="item in area.channelsData"
                       :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="终端联系人">
          <el-row >
            <el-col :span="13"><div class="grid-content bg-purple"><el-input style="" placeholder="联系人" v-model="formMineSet.contactName"></el-input></div></el-col>
            <el-col :span="11"><div class="grid-content bg-purple"><el-input style=""  placeholder="联系人电话" v-model="formMineSet.contactPhone"></el-input></div></el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="描述">
          <el-input :autosize="{ minRows: 6, maxRows: 8}" type="textarea" v-model="formMineSet.description"></el-input>
        </el-form-item>
        <el-form-item style="text-align:center;margin:10px 0">
          <el-button @click="dialogVisibleUpdate = false" >取消</el-button>
          <el-button type="primary" v-if="this.isNewData" @click="createShopSet">确定保存</el-button>
          <el-button type="primary" v-else @click="saveShopSet">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import * as opreate from 'api/getData'
  import { downLoadDoc } from 'utils/mUtils'
  import { mapState } from 'vuex'
  const formSet = {
    status: '',
    district:'',
    detailAddress:'',
    shopName: '',
    shopNumber: '',
    channelName: '',
    organizationName: '',
    region: '',
    city: '',
    province: '',
    description: '',
    contactName: '',
    contactPhone: '',
    shopImage: ''
  }

  export default {
    name: 'channelManagement',
    data () {
      return {
        showFlag: true,
        fileList2: [
        ],
        headersSet: {
          dipsToken: sessionStorage.getItem("tokenName")
        },
        dataSetParam1:{
          type: 'Document'
        },
        uploadimg: false,
        fileList:[],
        channelType: '全部',
        isNewData: false,
        select:{
            channelName: null
        },
        dataSetParam:{
          type: 'Document',
          userId:''
        },
        formMineSet: Object.assign({}, formSet),
        brandId:'',
        dialogVisible: false,
        dialogVisible1: false,
        dialogVisibleUpdate: false,
        tableDataSet: [],
        totalRecord:1,
        getTOrganizations: [],
        pageNumber: 1,
        area:{
            area: null,
            province: null,
            city:null,
            districts:'',
            chooseArea: '全部',
            chooseProvince: '全部',
            chooseCity: '全部',
            channelsData: null,
            area1: null,
            city1: null,
            province1: null
        },
        imgUrl: '',
        updateTitle: '添加终端门店'
      }
    },
    filters: {
     statusFilter(status) {
       const statusMap = { 启用:'success', 停用:'info' }
       return statusMap[status]
     }
    },
    computed:{
      ...mapState(["user"])
    },
    mounted () {
      this.dataSetParam.userId = this.user.phone
      this.getAreaSet()
    },
    methods: {
      beforeAvatarUpload(file){
        let mineSetFlag = file.type.includes('image')
        if(!mineSetFlag){
          this.$message.error('上传文件只能是图片文件')
        }
        return mineSetFlag
      },
      handleRemove () {
          this.formMineSet.shopImage = ''
      },
      downLoadDoc(name){
        downLoadDoc(name)
      },
      handleSuccessWord(res,file){
        if(res.code == '200'){
          switch (res.number) {
            case "-4":
              this.$message.error('导入模板无数据，请重试')
              break
            case "-3":
              this.$message.error('导入模板失败，请重试')
              break
            case "-1":
              this.$message.error('导入模板失败，请重试')
              break
            case "-2":
              this.$message.error('导入模板失败，请重试')
              break
            default:
              this.$message.success('成功导入模板，失败条数'+ res.number +'条');
              break
          }
        }else {
          this.$message.error('导入模板失败，请重试')
        }
      },
      createShopSet() {
        if(this.formMineSet.shopNumber.trim()){
          opreate.createShop({phone:this.user.phone, ...this.formMineSet }).then(res => {
            if(res.data == 'SUCCESS'){
              this.$message.success('创建成功');
              this.dialogVisibleUpdate = false
            }
            if(res.data == 'shopNumber已经存在'){
              this.$message.error('终端编号已经存在')
            }
          })
        }else {
          this.$message.error('终端编号不能为空');
        }
      },
      saveShopSet() {
        if(this.formMineSet.shopNumber.trim()){
          this.formMineSet.shopId = this.formMineSet.shopIdString
          opreate.updateShopStatus({ ...this.formMineSet, phone:this.dataSetParam.userId }).then(res => {
            if('200' == res.code){
              if(res.data == 'shopNumber已经存在'){
                this.$message.error('终端编号已经存在');
              }else {
                this.dialogVisibleUpdate = false
                this.$message.success('操作成功');
                this.getDataPage()
              }
            }else {
              this.$message.error('操作失败');
            }
          })
        }else {
          this.$message.error('终端编号不能为空');
        }
      },
      imgSuccess (success,error) {
          this.formMineSet.shopImage = success.fileUrl
      },
      addTerminalSet() {
        this.fileList2 = []
        Object.assign(this.formMineSet, formSet)
        opreate.getInfoByOragin({
          phone: this.dataSetParam.userId
        }).then(res => {
          this.getTOrganizations = res.data
        })
        this.isNewData = true
        this.updateTitle = '添加终端门店'
        this.dialogVisibleUpdate = true
        this.getAreaUpdate()
      },
      getShopChannelData(param){
        opreate.getShopChannelData({
          ...param,
          flag: 0,
          phone:this.dataSetParam.userId
        }).then(res => {
          this.area.channelsData = res.data
        })
      },
      getTOrganizationDetail(shopId) {
        this.isNewData = false
        this.showFlag = false
        this.getAreaUpdate()
        opreate.editShopInfo({ shopId }).then(res => {
          this.formMineSet = res.data[0] || {}
          this.fileList2 = [{
            name: this.formMineSet.shopName,
            url : this.formMineSet.shopImage
          }]
          this.showFlag = true
        })
        this.updateTitle = '编辑终端门店'
        this.dialogVisibleUpdate = true
        opreate.getInfoByOragin({
          phone:this.dataSetParam.userId
        }).then(res => {
          this.getTOrganizations = res.data
        })
        this.getDistrict()
      },
      getAreaSet() {
        opreate.getChannelRegion({}).then(res => {
          this.area.area =  [ '全部', ...res.data ]
          this.area.area1 = this.area.area
          this.getProvinceSet()
        })
      },
      getAreaUpdate() {
        opreate.getChannelRegion({}).then(res => {
          this.area.area1 = res.data
          this.getProvinceUpdate()
        })
      },
      getChannels() {
        opreate.getSaleOnlineSend({}).then(res => {
          this.area.channelsData = res.data.list
        })
      },
      getProvinceSet(region) {
        opreate.getChannelProvince({ region }).then(res => {
          this.area.chooseProvince = '全部'
          this.area.province =  [ '全部', ...res.data ]
          this.getCitySet()
        })
      },
      getCitySet(){
        opreate.getChannelCity({
          province:this.area.chooseProvince,
          region: this.area.chooseArea
        }).then(res => {
          this.area.chooseCity = '全部'
          this.area.city = [ '全部', ...res.data ]
          this.getDataPage()
        })
      },
      getProvinceUpdate(region) {
        opreate.getChannelProvince({ region }).then(res => {
          this.area.province1 =  res.data
          this.getCityUpdate()
        })
      },
      getCityUpdate(newVal) {
        opreate.getChannelCity({
          province:this.formMineSet.province,
          region: this.formMineSet.region
        }).then(res => {
          this.area.city1 = res.data
          this.getDistrict()
        })
      },
      getDistrict(){
        let { province,region, city } = this.formMineSet
        opreate.getAreaByParam({ province,region, city }).then(res => {
          this.area.districts = res.data
          this.getShopChannelData({ province,region, city })
        })
      },
      editShop(shopId,status) {
        let statusInfo = '启用' == status ? '停用' : '启用'
        opreate.updateShopStatus({ shopId: shopId, phone: this.user.phone, status: statusInfo }).then(res => {
          this.$message.success('操作成功')
          this.getDataPage()
        })
      },
      getDataPage(pageNumber = 1) {
        let { chooseArea, chooseProvince, chooseCity } = this.area
        opreate.getShopInfoManage({
          region: chooseArea == '全部'? null : chooseArea,
          province: chooseProvince == '全部'? null : chooseProvince,
          city: chooseCity == '全部'? null : chooseCity,
          channelType: this.channelType == '全部'? null : this.channelType,
          pageNumber: pageNumber,
          channelName:this.select.channelName == ''? undefined : this.select.channelName,
          phone:this.dataSetParam.userId,
          sort:'desc'
        }).then((res) => {
          if('200' == res.code){
            let { listA = [], totalRecord = 0, currentPage = 0 } = res.data.page || {}
            this.tableDataSet = listA || []
            this.pageNumber = currentPage || 0
            this.totalRecord = totalRecord || 0
          }else {
            this.$message.error('系统查询出错，请稍后再试')
          }
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .pickerOption {
    display: flex;
    align-items: center;
    float: right;
  }
  .pickerOptionSet{
    display: flex;
    justify-content:
      space-between;
    align-items: center;
  }
  .el-icon-plus+input{
      display:none !important;
  }
  output {
    display: none !important;
  }
  .el-form-item{
    margin-bottom: 15px;
  }
</style>

